﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using System.Threading;

using Gift.DAL;
using Gift.Model;
using System.Data;
using System.Text;
using System.Xml;
using Gift.WebApp;

namespace WebApp.admin.goods
{
    public partial class categoryList : BaseAdmin
    {

  

        protected string kw = "";
        protected string order = "sortOrder";
        protected int ot = 0;
        protected int pageCount = 0;
        protected int pageIndex = 1;
        protected int pageSize = 20;
        protected string parentType = "";
        protected string pid = "00000000-0000-0000-0000-000000000000";
        protected PageList pl = new PageList();
        protected int t = 0;
        protected int total = 0;
        bool _isEdit = false;
        bool _isDeleted = false;
        string _addDisplay = "none";

        public string AddDisplay
        {
            get { return _addDisplay; }
        }

        // Methods
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            string parentId = base.Request.Form["Item"];
            if (parentId.Contains(","))
            {
                Array array = parentId.Split(new char[] { ',' });
                foreach (string str2 in array)
                {
                    if (BaseFactory.theCategory.GetCategoryByParentIdAndCompanyIdAndIsShow(str2, int.Parse(base.Administrator.CompanyId), -1).Rows.Count == 0)
                    {

                        BaseFactory.theCategory.Delete(Guid.Parse(str2));
                        base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除成功！');</script>");
                    }
                    else
                    {
                        base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('请先删除下级分类！');</script>");
                    }
                }
            }
            else if (BaseFactory.theCategory.GetCategoryByParentIdAndCompanyIdAndIsShow(parentId, int.Parse(base.Administrator.CompanyId), -1).Rows.Count == 0)
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除成功！');</script>");
                BaseFactory.theCategory.Delete(Guid.Parse(parentId));
            }
            else
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('请先删除下级分类！');</script>");
            }
            base.Response.Redirect(HttpContext.Current.Request.Url.PathAndQuery);
        }

        void DeleteItem()
        {
            if (Request.QueryString["action"] == "del")
            {
                string parentId = Request.QueryString["id"];
                if (BaseFactory.theCategory.GetCategoryByParentIdAndCompanyIdAndIsShow(parentId, int.Parse(base.Administrator.CompanyId), -1).Rows.Count == 0)
                {
                    BaseFactory.theCategory.Delete(Guid.Parse(parentId));
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除成功！');</script>");
                }
                else
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('请先删除下级分类！');</script>");
                }
            }
        }

        private void CategoryBind()
        {
            try
            {
                if (base.Request.QueryString["p"] != null)
                {
                    this.pageIndex = int.Parse(base.Request.QueryString["p"]);
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    this.pageSize = Convert.ToInt32(base.Request.QueryString["ps"]);
                }
                if (base.Request.QueryString["or"] != null)
                {
                    this.order = base.Request.QueryString["or"];
                }
                if (base.Request.QueryString["ot"] != null)
                {
                    this.ot = Convert.ToInt32(base.Request.QueryString["ot"]);
                }
                if (base.Request.QueryString["pid"] != null)
                {
                    this.pid = base.Request.QueryString["pid"];
                }
                this.pl.TblName = "tbCategory";
                this.pl.StrGetFields = "id,categoryIdentity,parentId,categoryName,sortOrder,isShow,convert(nvarchar(10),createTime,121) as createTime";
                this.pl.FldName = this.order;
                this.pl.PageSize = this.pageSize;
                this.pl.PageIndex = this.pageIndex;
                this.pl.DoCount = 1;
                this.pl.OrderType = this.ot;
                if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
                {
                    this.kw = base.Request.QueryString["kw"];
                    this.pl.StrWhere = base.Request.QueryString["t"] + " like '%" + this.kw + "%' and parentId='" + this.pid + "' and companyid=" + base.Administrator.CompanyId + "";
                }
                else
                {
                    this.pl.StrWhere = "parentId='" + this.pid + "' and companyId=" + base.Administrator.CompanyId + "";
                }
                this.total = Convert.ToInt32(BaseFactory.thePageList.GetPageList(this.pl).Rows[0]["Total"]);
                this.pl.DoCount = 0;
                DataTable pageList = BaseFactory.thePageList.GetPageList(this.pl);
                new PageListNo().DelPageSize(pageList, this.total);
                if (pageList.Rows.Count == 0)
                {
                    this.btnDelete.Visible = false;
                }
                this.rptCategory.DataSource = pageList.DefaultView;
                this.rptCategory.DataBind();
            }
            catch
            {
            }
        }

        protected string GetParentType(object pid)
        {
            string str = "";
            DataTable categoryById = BaseFactory.theCategory.GetCategoryById(pid.ToString());
            if (categoryById.Rows.Count > 0)
            {
                str = categoryById.Rows[0]["categoryName"].ToString();
            }
            return str;
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            byte[] inArray = ViewStateCompression.DeCompress(Convert.FromBase64String(base.Request.Form.Get("__MSPVSTATE")));
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(Convert.ToBase64String(inArray));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
         
            if (!base.IsPostBack)
            {
                this.ValidateLoginUser();
                this.DeleteItem();
                if (base.Request.QueryString["t"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sT", "<script type=\"text/javascript\">selectIsExitItem(\"selectType\",\"" + base.Request.QueryString["t"] + "\");</script>");
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sPs", "<script type=\"text/javascript\">selectIsExitItem(\"selectPageSize\",\"" + base.Request.QueryString["ps"] + "\");</script>");
                }
                if (base.Request.QueryString["pid"] != null)
                {
                    if (base.Request.QueryString["pid"] != "00000000-0000-0000-0000-000000000000")
                    {
                        DataTable categoryById = BaseFactory.theCategory.GetCategoryById(base.Request.QueryString["pid"]);
                        if (categoryById.Rows.Count > 0)
                        {
                            this.parentType = "categoryList.aspx?pid=" + categoryById.Rows[0]["parentId"].ToString();
                        }
                    }
                    else
                    {
                        base.ClientScript.RegisterStartupScript(base.GetType(), "ssm", "document.getElementById(\"btnParentType\").style.display=\"none\";", true);
                    }
                }
                else
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "ssm", "document.getElementById(\"btnParentType\").style.display=\"none\";", true);
                }
                this.btnDelete.Attributes.Add("disabled", "disabled");
                this.CategoryBind();
            }
        }



        protected void rptCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            base.SetListPerssion(e, _isEdit, _isDeleted);

        }

        void ValidateLoginUser()
        {
            if (!base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsCategoryList))
            {
                base.Response.Write("<script language=javascript>window.top.location.href='../login.aspx';</script>");
                base.Response.End();
            }
            if (base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsCategoryAdd))
            {
                _addDisplay = "block";
            }
            if (base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsCategoryEdit))
            {
                _isEdit = true;
            }
            if (base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsCategoryDeleted))
            {
                _isDeleted = true;
            }

        }

     

        protected override void SavePageStateToPersistenceMedium(object pViewState)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter output = new StringWriter();
            formatter.Serialize(output, pViewState);
            string hiddenFieldInitialValue = Convert.ToBase64String(ViewStateCompression.Compress(Convert.FromBase64String(output.ToString())));
            base.ClientScript.RegisterHiddenField("__MSPVSTATE", hiddenFieldInitialValue);
        }

    }
}